<template>
  <view class="content">
    <!-- 用户登录部分 -->
    <view class="user-group">
      <button @click="loginUser('user1')">登录用户1</button>
      <button @click="loginUser('user2')">登录用户2</button>
      <button @click="loginUser('user3')">登录用户3</button>
    </view>

    <!-- 消息发送部分 -->
    <view class="send-group">
      <select  class="sender-select">
        <option value="">选择发送者</option>
        <option v-for="user in connectedUsers" :value="user">{{ user }}</option>
      </select>
      <input v-model="targetUserId" placeholder="目标用户ID" class="target-input" />
      <input v-model="message" placeholder="输入消息" class="message-input" />
      <button @click="sendMessage" >发送</button>
    </view>

    <!-- 统一消息展示 -->
    <view class="messages">
      <view v-for="(msg, index) in messages" :key="index" class="message-item">
        {{ msg }}
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import { http } from '../../utils/requestUtil'
import { login } from '../../utils/tokenUtil'

// 用户列表，添加重连相关属性
const users = reactive({
  user1: { 
    username: 'test1', 
    password: '12345', 
    token: '', 
    userId: '101', 
    socket: null, 
    reconnecting: false, 
    reconnectTimer: null,
    reconnectInterval: 1000 // 初始重连间隔1秒
  },
  user2: { 
    username: 'test2', 
    password: '12345', 
    token: '', 
    userId: '102', 
    socket: null, 
    reconnecting: false, 
    reconnectTimer: null,
    reconnectInterval: 1000
  },
  user3: { 
    username: 'test3', 
    password: '12345', 
    token: '', 
    userId: '103', 
    socket: null, 
    reconnecting: false, 
    reconnectTimer: null,
    reconnectInterval: 1000
  }
})

const currentSender = ref('')
const targetUserId = ref('')
const message = ref('')
const messages = ref([])
const connectedUsers = ref([])

const loginUser = async (username) => {
  try {
    const user = users[username]
    // 清除可能存在的旧重连定时器
    clearReconnectTimer(user)
    
    const res = await login(user.username, user.password)
    user.token = uni.getStorageSync('token');
    
    initWebSocket(user)
    connectedUsers.value = Object.keys(users).filter(u => users[u].token)
    uni.showToast({ title: `${username} 登录成功`, icon: 'success' })
  } catch (error) {
    uni.showToast({ title: `${username} 登录失败`, icon: 'error' })
  }
}

const initWebSocket = (user) => {
  const socketTask = uni.connectSocket({
    url: `ws://localhost:8080/ws/endpoint/${user.token}`,
    success: () => {
      console.log(`${user.username} 连接创建成功`)
    }
  })

  // 连接打开时的处理
  socketTask.onOpen(() => {
    messages.value.push(`系统：${user.username} 连接成功`)
    // 连接成功后重置重连间隔
    user.reconnectInterval = 1000
  })

  // 接收消息处理（保持原有逻辑）
  socketTask.onMessage((res) => {
    try {
      const data = JSON.parse(res.data)
      messages.value.push(`[${user.username}] 收到 ${data.fromUserId} 的消息：${data.content}`)
    } catch {
      messages.value.push(`[${user.username}] 收到：${res.data}`)
    }
  })

  // 错误处理，触发重连
  socketTask.onError((err) => {
    messages.value.push(`系统：${user.username} 连接出错，准备重连...`)
    startReconnect(user, socketTask)
  })

  // 连接关闭处理，触发重连（非主动关闭时）
  socketTask.onClose((res) => {
    if (res.code !== 1000) { // 1000是正常关闭代码
      messages.value.push(`系统：${user.username} 连接断开，状态码：${res.code}，准备重连...`)
      startReconnect(user, socketTask)
    } else {
      messages.value.push(`系统：${user.username} 连接已正常关闭`)
    }
  })

  user.socket = socketTask
}

// 启动重连逻辑
const startReconnect = (user, oldSocket) => {
  if (user.reconnecting || !user.token) return // 避免重复重连或无token时重连
  
  // 清除旧连接
  oldSocket?.close()
  user.socket = null
  
  user.reconnecting = true
  // 使用指数退避算法计算重连间隔
  const maxInterval = 30000 // 最大重连间隔30秒
  user.reconnectInterval = Math.min(user.reconnectInterval * 2, maxInterval)
  
  user.reconnectTimer = setTimeout(() => {
    messages.value.push(`系统：${user.username} 尝试第${getReconnectCount(user)}次重连（间隔${user.reconnectInterval/1000}秒）`)
    initWebSocket(user) // 重新初始化连接
    user.reconnecting = false
  }, user.reconnectInterval)
}

// 获取重连次数（通过定时器ID的时间戳计算，这里简化处理）
const getReconnectCount = (user) => {
  return Math.floor(Math.log2(user.reconnectInterval / 1000)) + 1
}

// 清除重连定时器
const clearReconnectTimer = (user) => {
  clearTimeout(user.reconnectTimer)
  user.reconnectTimer = null
  user.reconnecting = false
}

// 发送消息处理（保持原有逻辑，增加连接状态检查）
const sendMessage = () => {
  if (!message.value.trim() || !targetUserId.value) return

  const user = users[currentSender.value]
  if (!user?.socket || user.reconnecting) { // 重连中时不发送
    messages.value.push(`系统：${user.username} 连接中，请稍后再试`)
    return
  }

  const msgData = JSON.stringify({
    fromUserId: user.userId,
    toUserId: targetUserId.value,
    content: message.value.trim()
  })

  user.socket.send({
    data: msgData,
    success: () => {
      messages.value.push(`[${user.username}] 发送给 ${targetUserId.value}：${message.value.trim()}`)
      message.value = ''
    },
    fail: (err) => {
      messages.value.push(`[${user.username}] 发送消息失败：${err.errMsg}`)
      console.error('WebSocket 消息发送失败', err);
      startReconnect(user, user.socket) // 发送失败时触发重连
    }
  })
}

// 组件卸载时清除所有重连定时器
onUnmounted(() => {
  Object.values(users).forEach(user => {
    clearReconnectTimer(user)
    user.socket?.close()
  })
})
</script>

<style>
/* 保持原有样式不变 */
.content {
  padding: 20px;
}

.user-group button {
  margin: 5px;
  padding: 8px;
}

.send-group {
  margin: 15px 0;
  display: flex;
  gap: 5px;
}

.sender-select, .target-input, .message-input {
  flex: 1;
  border: 1px solid #ccc;
  padding: 8px;
}

.messages {
  margin-top: 20px;
  border-top: 1px solid #eee;
}

.message-item {
  padding: 8px;
  border-bottom: 1px solid #eee;
}
</style>
